import { getTree } from "../communicate/AjaxPart.js";
import { TOC, md } from "../all.js";
import renderMarkdown from "./markdown.js";

function renderTree(arr, lastPath) {
    let content = arr.files
        .map((i) => {
            return i.type === "directory"
                ? renderTree(i, (lastPath + "/" + i.name + "/").replace("//", "/"))
                : `<span data-path='${(lastPath + i.name).replace("//", "/")}' class='tocList'>${i.name}</span>`;
        })
        .join("");
    return `<details open data-path='${lastPath}'><summary>${arr.name}</summary>${content}</details>`;
}

async function toc(packageName, version, root) {
    let tree = await getTree(packageName, version);
    root.split(/\.*\//)
        .filter((i) => (i ? true : i === 0 ? true : false))
        .forEach((i) => {
            tree = tree.reduce((a, b) => (b.name == i ? b : a));
        });

    TOC.innerHTML = renderTree(tree, root);
    [...TOC.querySelectorAll(".tocList")].forEach((i) => i.addEventListener("click", tocList));
}

function tocList(e) {
    console.log(e.target.dataset.path);
    md.classList.toggle("animate__fadeInUp");
    setTimeout(() => {
        md.classList.add("animate__fadeInUp");
    }, 1);
    md.innerHTML = "";
    renderMarkdown(Setting.packageName, Setting.version, e.target.dataset.path);
}
export default toc;
